package com.eminem.controller.user;


import com.eminem.common.StrMath;
import com.eminem.controller.BaseServlet;
import com.eminem.model.UserFocus;
import com.eminem.service.DeptService;
import com.eminem.service.UserService;
import com.eminem.service.impl.DeptServiceimpl;
import com.eminem.service.impl.UserServletimpl;
import com.eminem.utils.PageUtil;
import com.eminem.utils.StrUtil;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItem;


import javax.servlet.annotation.WebServlet;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@WebServlet("/user/*")
public class UserController extends BaseServlet {

    private UserService userService = new UserServletimpl();

    private DeptService deptService = new DeptServiceimpl();


    public void look(HttpServletRequest req, HttpServletResponse resp){
        try {
            String id = req.getParameter("userId");
            Map<String, Object> map = userService.getUserInfo(id);
            req.setAttribute("userInfo",map);
            req.setAttribute("deptList",deptService.getDeptInfo());
            req.getRequestDispatcher("/html/user_look.jsp").forward(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void getUser(HttpServletRequest req, HttpServletResponse resp){
        try {
            String page = req.getParameter("page");
            String name = req.getParameter("name");
            int currentPage = 1;
            if (null != page){
                currentPage = Integer.parseInt(page);
            }

            //登录会话作用域拿到数据
//            Map userInfo = (Map)req.getSession().getAttribute("UserInfo");
            String userId = getUserId(req);
//            System.out.println(userId);

            List<Map<String,Object>> userList = userService.getUserList(userId,currentPage,name);
            req.setAttribute("userList",userList);
            //用户总数
            long userCount = userService.getUserCount(name);
            //总分页
            long pageTotal = PageUtil.PageTotal(userCount);
            //起始页
            long startPage = PageUtil.getStartPage(currentPage);
            //结束页
            long endPage = PageUtil.getEndPage(currentPage, userCount);
            req.setAttribute("currentPage",currentPage);
            req.setAttribute("name",name);
            req.setAttribute("userCount",userCount);
            req.setAttribute("pageTotal",pageTotal);
            req.setAttribute("pageCount",StrMath.PAGE_COUNT);
            req.setAttribute("startPage",startPage);
            req.setAttribute("endPage",endPage);


            req.getRequestDispatcher("/html/user.jsp").forward(req,resp);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void followUser(HttpServletRequest req, HttpServletResponse resp){
        try {
            //关注id
            String ufId = req.getParameter("ufId");
//            System.out.println(ufId);
            //登录id
            String userId = getUserId(req);
//            System.out.println(userId);
            if (userId.equals(ufId)){
                resp.getWriter().write("不能关注自己");
//                System.out.println("不能关注自己");
            }else {
                UserFocus focus = userService.getFollowUser(userId,ufId);
                if (null != focus){
                    resp.getWriter().write("已经关注了") ;
//                    System.out.println("已经关注了");
                }else {
                    boolean b = userService.followUser(userId,ufId);
                    if (b){
                        resp.getWriter().write("1");
//                        System.out.println("关注成功");
                    }else {
                        resp.getWriter().write("关注失败");
//                        System.out.println("关注失败");
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void  unfollowUser(HttpServletRequest req, HttpServletResponse resp){
        try {
            //关注id
            String ufId = req.getParameter("ufId");
            //登录id
            String userId = getUserId(req);
            UserFocus focus = userService.getFollowUser(userId,ufId);
            if (null != focus){
                boolean b = userService.unfollowUser(focus.getId());
                if (b){
                    //取消关注成功
                    resp.getWriter().write("1");
                }else {
                    resp.getWriter().write("    取消关注失败");
                }
            }else {
                resp.getWriter().write("关注成功");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void upload(HttpServletRequest req, HttpServletResponse resp){
        try {
            InputStream is = null;
            FileOutputStream fos = null;
            String fileName = StrUtil.getUUId()+ StrMath.IMG_END;
            try {
                ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory());
                List<FileItem> items = fileUpload.parseRequest(req);
                if (!items.isEmpty()){
                    FileItem file = items.get(0);
                    //图片文件名
                    String name = file.getName();
                    if (!name.contains(StrMath.IMG_END)){
                        resp.getWriter().write(req.getContextPath()+StrMath.DEFAULT_PATH);
                        return;
                    }
                    is = file.getInputStream();
                    //图片名

                    fos = new FileOutputStream(StrMath.FILE_PATH + fileName);
                    byte[] bytes = new byte[4 * 1024];
                    int len;
                    while (-1 != (len = is.read(bytes))){
                        fos.write(bytes,0,len);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                resp.getWriter().write("上传图片失败");
            } finally {
                if (null != fos){
                    fos.close();
                }
                if (null != is){
                    is.close();
                }
            }
            //更新图片到数据库，而且更新会话作用域的数据
            String userId = getUserId(req);
            userService.uploadImg(userId,StrMath.IN_FILE_PATH + fileName);
            Map<String, Object> map = userService.findUserInfo(getUserName(req));
            req.getSession().setAttribute("UserInfo",map);
            resp.getWriter().write(StrMath.IN_FILE_PATH + fileName);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void myUser(HttpServletRequest req, HttpServletResponse resp){
        try {
            //拿到登录用户id
            String userId = getUserId(req);
            String page = req.getParameter("page");
            int currentPage = 1;
            if (null != page){
                currentPage = Integer.parseInt(page);
            }
            List<Map<String, Object>> list = userService.getUserName(userId,currentPage);
            req.setAttribute("list",list);

            //关注总数量
            long Fcount = userService.getFollowCount(userId);
            //总分页
            long pageTotal = PageUtil.PageTotal(Fcount);
//            System.out.println(pageTotal);
            //起始页
            long startPage = PageUtil.getStartPage(currentPage);
//            System.out.println(startPage);
            //结束页
            long endPage = PageUtil.getEndPage(currentPage, Fcount);
//            System.out.println(endPage);
            req.setAttribute("currentPage",currentPage);
            req.setAttribute("userCount",Fcount);
            req.setAttribute("pageTotal",pageTotal);
            req.setAttribute("pageCount",StrMath.PAGE_COUNT);
            req.setAttribute("startPage",startPage);
            req.setAttribute("endPage",endPage);
            req.getRequestDispatcher("/html/my_user.jsp").forward(req,resp);

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}
